//Title:        IntegriSign Capture SDK.
//Company:      IntegriSign.
//Description:  Sample application demonstrating IntegriSign Desktop component usage

/*
 THE FOLLOWING SAMPLE (DeskSignTest.java) DEMONSTRATES THE USAGE OF SIGNATURE COMPONET
 FOR SIGNATURE CAPTURE AND CONTENT BINDING TO THE SIGNATURE. DeskSignTest IMPLEMENTS THE IDocInfo INTERFACE WHICH IS A REQUIREMENT.
 USING THE METHODS OF IDocInfo INTERFACE METHODS FORM DATA IS BINDED TO THE SIGNATURE
 (ONE WAY HASH IS GEERATED). INCASE NO DATA BINDING IS REQUIRED NULL IMPLEMENTATION SHOULD
 BE GIVEN TO ALL THE METHODS OF IDocInfo INTERFACE IN THIS CLASS


 */

import java.awt.*;
import javax.swing.*;
import java.awt.event.*; 
import java.io.FileOutputStream;
import integrisign.desktop.*;
import integrisign.*;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;


public class DeskSignTest extends JFrame implements IDocInfo {
    JLabel jname = new JLabel();
    JLabel jmessage = new JLabel();
    JTextField jTextFieldName = new JTextField();
    JTextField jTextFieldMsg = new JTextField();
    JLabel jsignature = new JLabel();
    DeskSign deskSign1 = new DeskSign();
    JButton jsignnow = new JButton();
    JButton jgetsigndata = new JButton();
    JButton jclearsign = new JButton();
    JButton jopensign = new JButton();
    JButton jVintegrity = new JButton();
    JButton jsaveimages = new JButton();
    String signstr;

    JLabel integrisigninfo = new JLabel();
    JCheckBox jCheckBoxwhiteSpaceRemoval = new JCheckBox();
    JCheckBox jCheckBoxMaxEnlargeFactor = new JCheckBox();
    JTextField jTextFieldFactor = new JTextField();
    JSpinner jSpinthickness = new JSpinner();
    JLabel jLabel2 = new JLabel();
    JCheckBox jCheckBoxlcdopts = new JCheckBox();
    public DeskSignTest(String title) {
        super(title);
        try {
            jbInit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void jbInit() throws Exception {
        jname.setText("Name");
        jname.setBounds(new Rectangle(8, 22, 115, 20));
        this.getContentPane().setLayout(null);
        //jname.setBounds(19,30,115,20);
        jmessage.setText("Message");
        jmessage.setBounds(new Rectangle(7, 53, 115, 20));
        jTextFieldMsg.setBounds(new Rectangle(181, 56, 182, 20));
        jsignature.setText("Signature");
        jsignature.setBounds(new Rectangle(7, 97, 118, 17));
        deskSign1.setOpaque(true);
        deskSign1.setBounds(new Rectangle(180, 90, 181, 80));
        jsignnow.setText("SignNow");
        jsignnow.setBounds(new Rectangle(11, 234, 113, 25));
        jsignnow.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(ActionEvent e) {
                jsignnow_actionPerformed(e);
            }
        });
        jgetsigndata.setText("GetSignData");
        jgetsigndata.setBounds(new Rectangle(142, 234, 113, 25));
        jgetsigndata.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(ActionEvent e) {
                jgetsigndata_actionPerformed(e);
            }
        });
        jclearsign.setText("ClearSign");
        jclearsign.setBounds(new Rectangle(272, 234, 113, 25));
        jclearsign.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(ActionEvent e) {
                jclearsign_actionPerformed(e);
            }
        });
        jopensign.setText("OpenSign");
        jopensign.setBounds(new Rectangle(11, 274, 113, 25));
        jopensign.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(ActionEvent e) {
                jopensign_actionPerformed(e);
            }
        });
        jVintegrity.setText("VerifyContent");
        jVintegrity.setBounds(new Rectangle(141, 274, 113, 25));
        jVintegrity.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(ActionEvent e) {
                jVintegrity_actionPerformed(e);
            }
        });
        jsaveimages.setText("SaveImages");
        jsaveimages.setBounds(new Rectangle(272, 274, 113, 25));
        jsaveimages.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(ActionEvent e) {
                jsaveimages_actionPerformed(e);
            }
        });
        integrisigninfo.setFont(new java.awt.Font("Dialog", Font.BOLD, 14));
        integrisigninfo.setText("Demo built using IntegriSign DeskSign");
        integrisigninfo.setBounds(new Rectangle(61, 318, 278, 25));
        this.getContentPane().setBackground(SystemColor.scrollbar);

        this.setFont(new java.awt.Font("Dialog", 0, 10));
        this.setResizable(false);
        jCheckBoxwhiteSpaceRemoval.setBackground(new Color(212, 208, 200));
        jCheckBoxwhiteSpaceRemoval.setSelected(true);
        jCheckBoxwhiteSpaceRemoval.setText("White space removal");
        jCheckBoxwhiteSpaceRemoval.setBounds(new Rectangle(175, 178, 180, 16));
        jCheckBoxwhiteSpaceRemoval.addChangeListener(new ChangeListener() {
            public void stateChanged(ChangeEvent e) {
                jCheckBoxwhiteSpaceRemoval_stateChanged(e);
            }
        });
        jCheckBoxMaxEnlargeFactor.setBackground(SystemColor.scrollbar);
        jCheckBoxMaxEnlargeFactor.setSelected(true);
        jCheckBoxMaxEnlargeFactor.setText("Max enlargement factor");
        jCheckBoxMaxEnlargeFactor.setBounds(new Rectangle(175, 203, 163, 18));
        jCheckBoxMaxEnlargeFactor.addChangeListener(new ChangeListener() {
            public void stateChanged(ChangeEvent e) {
                jCheckBoxMaxEnlargeFacto_stateChanged(e);
            }
        });
        jTextFieldFactor.setText("1.25");
        jTextFieldFactor.setBounds(new Rectangle(347, 203, 32, 18));
        //jTextField3.setBounds(250,211,165,18);
        jTextFieldName.setBounds(new Rectangle(180, 22, 184, 20));
        jSpinthickness.setBounds(new Rectangle(92, 203, 35, 22));
        String[] thicknessValues = {"1", "2", "3", "4", "5", "6", "7", "8", "9"};
        SpinnerListModel thicknessModel = new SpinnerListModel(thicknessValues);
        jSpinthickness.setModel(thicknessModel);
        jSpinthickness.setValue("2");
        JFormattedTextField tf = ((JSpinner.DefaultEditor) jSpinthickness.getEditor()).
                                 getTextField();
        tf.setEditable(false);
        tf.setBackground(Color.white);
        jLabel2.setText("Sign thickness");
        jLabel2.setBounds(new Rectangle(7, 203, 95, 22));
        jCheckBoxlcdopts.setBackground(new Color(212, 208, 200));
        jCheckBoxlcdopts.setSelected(true);
        jCheckBoxlcdopts.setText("Show buttons on LCD");
        jCheckBoxlcdopts.setBounds(new Rectangle(4, 179, 166, 16));
        this.getContentPane().add(jTextFieldMsg, null);
        this.getContentPane().add(deskSign1, null);
        this.getContentPane().add(jTextFieldName, null);
        this.getContentPane().add(jCheckBoxMaxEnlargeFactor);
        this.getContentPane().add(jCheckBoxwhiteSpaceRemoval);
        this.getContentPane().add(jTextFieldFactor);
        this.getContentPane().add(jmessage, null);
        this.getContentPane().add(jsignature, null);
        this.getContentPane().add(jname, null);
        this.getContentPane().add(jVintegrity, null);
        this.getContentPane().add(jsignnow, null);
        this.getContentPane().add(jgetsigndata, null);
        this.getContentPane().add(jclearsign, null);
        this.getContentPane().add(jsaveimages, null);
        this.getContentPane().add(jopensign, null);
        this.getContentPane().add(jLabel2);
        this.getContentPane().add(jSpinthickness);
        this.getContentPane().add(jCheckBoxlcdopts);
        this.getContentPane().add(integrisigninfo, null);
    }

    private void setSignaturePreference() {
        byte thicknessVal = Byte.parseByte(jSpinthickness.getValue().toString());
        deskSign1.setSignThickness(thicknessVal);

        if (jCheckBoxwhiteSpaceRemoval.isSelected()) {
            deskSign1.enableWhiteSpaceRemoval(true);
            if(jCheckBoxMaxEnlargeFactor.isSelected())
            {
                deskSign1.enableMaxEnlargementFactor(true);
                if (jTextFieldFactor.getText().length() > 0) {
                    try {
                        float enlrgementFacor = Float.parseFloat(jTextFieldFactor.
                                getText());
                        if (enlrgementFacor < 1 || enlrgementFacor > 2) {
                            System.out.println("Invalid enlargement factor, valid value must be between 1.0 and 2.0. Setting it to default value 1.25");
                            jTextFieldFactor.setText("1.25");
                            jTextFieldFactor.updateUI();
                            deskSign1.setMaxEnlargementFactor(1.25f);
                            this.validate();
                            this.repaint();
                        }
                        deskSign1.setMaxEnlargementFactor(Float.parseFloat(
                                jTextFieldFactor.
                                getText()));
                    } catch (NumberFormatException numbEx) {
                        System.out.println("Invalid enlargement factor, valid value must be between 1.0 and 2.0. Setting it to default value 1.25");
                        jTextFieldFactor.setText("1.25");
                        deskSign1.setMaxEnlargementFactor(1.25f);

                    }
                }else
                {
                    jTextFieldFactor.setText("1.25");
                    deskSign1.setMaxEnlargementFactor(1.25f);
                }

            }
            else
                deskSign1.enableMaxEnlargementFactor(false);

        } else
        {
                        deskSign1.enableWhiteSpaceRemoval(false);
                        deskSign1.enableMaxEnlargementFactor(false);
        }

    }

    // ***********IMPLEMENTATION OF IDOCINFO INTERFACE************************

    //INCASE NO HASH IS REQUIRED THE FOLLOWING METHOD CAN BE NULL IMPLEMENTED

    public void feedGrabber(integrisign.IGrabber ig) {
        //BUILD THE HASH INFORMATION OF THE DATA THAT NEEDS TO BOUND TO SIGNATURE OBJECT
        String str = jTextFieldName.getText() + jTextFieldMsg.getText();
        ig.grabBytes(str.getBytes());
        ig.finishGrab();

    }

    //IMPLEMENT THIS METHOD AS IT IS
    public byte getVersion() {
        return 1;
    }

    public String getDocID() {
        return "";
    }

    // ***********IMPLEMENTATION OF IDOCINFO INTERFACE************************

    // START SIGNING CODE
    void jsignnow_actionPerformed(ActionEvent e) {
        // The following call sets the thickness to be used while drawing the
        // signature on the object and as well in the generated image.
        // This call can be invoked before invoking the image generation calls
        // if a different thickness is to be used for images.
        setSignaturePreference();
        deskSign1.setEnableLCDButtons(jCheckBoxlcdopts.isSelected());
        /* byte thicknessVal = Byte.parseByte(jSpinner1.getValue().toString());
         deskSign1.setSignThickness(thicknessVal);
         deskSign1.enableWhiteSpaceRemovalEnabled(jCheckBox1.isSelected());
         if (jCheckBox1.isSelected()) {
             deskSign1.enableMaxEnlargementFactor(jCheckBox2.isEnabled());
         }
         if (jCheckBox2.isSelected()) {
             if (jTextField3.getText().length() > 0) {
                 try {
                     deskSign1.setMaxEnlargementFactor(Float.parseFloat(
                             jTextField3.
                             getText()));
                 } catch (NumberFormatException numbEx) {
                     numbEx.printStackTrace();
                 }
             } else {
                 deskSign1.setMaxEnlargementFactor(1.25f);
             }
         }*/
        try {
            if (deskSign1.isSigned()) {
                deskSign1.clear();

                // To pass more information about the signer to the component refer to the API document
                // for Overloadedd sign Now call
                //deskSign1.signNowEx((IDocInfo)this);
                deskSign1.signNowEx("" + jTextFieldName.getText(), "", "", "", "", true,
                                    (IDocInfo)this);

            } else {
                signstr = "";
                //deskSign1.signNowEx((IDocInfo)this);
                //deskSign1.signNowEx((IDocInfo)this);
                deskSign1.signNowEx("" + jTextFieldName.getText(), "", "", "", "", true,
                                    (IDocInfo)this);
            }

        } catch (ValidationException vEx) {
            System.out.println("Name is required, please enter name");
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    // CLEARING CURRENT SIGNATURE
    void jclearsign_actionPerformed(ActionEvent e) {
        if (deskSign1.isSigned()) {
            deskSign1.clear();
        }

    }

//VERIFYING THE INTEGRITY OF THE DATA WHICH IS BOUND TO THE SIGNATURE
    void jVintegrity_actionPerformed(ActionEvent e) {
        if (deskSign1.isSigned()) {
            int result = deskSign1.verifyDocument(this);
        }

    }

// GETTING CURRENT SIGNATURE DATA
    void jgetsigndata_actionPerformed(ActionEvent e) {
        if (deskSign1.isSigned()) {
            signstr = deskSign1.getString();
        }
    }

// OPENING ALREADY CAPTURED AND STORED SIGNATURE FROM THE BASE64 ENCODED STRING
    void jopensign_actionPerformed(ActionEvent e) {
        if (signstr != "") {

            setSignaturePreference();
            deskSign1.openSign1(signstr);

        }

    }

    void jsaveimages_actionPerformed(ActionEvent e) {
        //save the Images in files as same as userid
        if (deskSign1.isSigned()) {
            setSignaturePreference();
            try {
                if (signstr != null && signstr.length() > 0) {
                    Base64Format b64fmt = new Base64Format();
                    byte[] bmpbytes = b64fmt.decode64(deskSign1.getBMPString(
                            signstr, 125, 85));
                    byte[] gifbytes = b64fmt.decode64(deskSign1.getGifString(
                            signstr, 125, 85));
                    byte[] jpegbytes = b64fmt.decode64(deskSign1.getJpegString(
                            signstr, 125, 85, 100));
                    byte[] pngbytes = b64fmt.decode64(deskSign1.getPNGString(
                            signstr, 125, 85, false));
                    String filename = jTextFieldName.getText();
                    FileOutputStream bmpfos = new FileOutputStream(filename +
                            ".bmp");
                    FileOutputStream giffos = new FileOutputStream(filename +
                            ".gif");
                    FileOutputStream jpegfos = new FileOutputStream(filename +
                            ".jpeg");
                    FileOutputStream pnggfos = new FileOutputStream(filename +
                            ".png");
                    bmpfos.write(bmpbytes);
                    giffos.write(gifbytes);
                    jpegfos.write(jpegbytes);
                    pnggfos.write(pngbytes);
                    bmpfos.close();
                    giffos.close();
                    jpegfos.close();
                    pnggfos.close();
                } else {
                    System.out.println("Signature data not available");
                }
            } catch (Exception ex1) {

            }

        }
    }

    public static void main(String[] args) {
        DeskSignTest deskSignTest = new DeskSignTest(
                "IntegriSign DeskSign Demo");
        deskSignTest.setSize(410, 385);
        deskSignTest.setVisible(true);

    }

    public void jCheckBoxwhiteSpaceRemoval_stateChanged(ChangeEvent e) {
        if (jCheckBoxwhiteSpaceRemoval.isSelected()) {
            jCheckBoxMaxEnlargeFactor.setEnabled(true);
            if(jCheckBoxMaxEnlargeFactor.isSelected())
                jTextFieldFactor.setEnabled(true);
            else
                jTextFieldFactor.setEnabled(false);
        } else {
            jCheckBoxMaxEnlargeFactor.setEnabled(false);
            jTextFieldFactor.setEnabled(false);
        }
    }

    public void jCheckBoxMaxEnlargeFacto_stateChanged(ChangeEvent e) {
        if (jCheckBoxMaxEnlargeFactor.isSelected()) {
            jTextFieldFactor.setEnabled(true);
        } else {
            jTextFieldFactor.setEnabled(false);
        }
    }
}
